package com.webserver.core;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 处理与指定客户端的一次HTTP交互
 * 完成一次交互由三步构成：
 * 1：解析请求
 * 2：处理请求
 * 3：响应客户端
 *
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            //1解析请求
            HttpRequest request = new HttpRequest(socket);
            HttpResponse response = new HttpResponse(socket);

            //2处理请求
            String path = request.getUri();
            File file = new File("./webapps" + path);

            //如果请求的资源存在并且是一个文件则正确
            if (file.exists() && file.isFile()) {
                response.setEntity(file);
            } else {
                response.setStatusCode(404);
                response.setStatusReason("Not Found");
                response.setEntity(new File("./webapps/root/404.html"));
            }


            //3发送响应
            response.flush();



            System.out.println("发送相应完毕！");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //一次HTTP交互完毕后要与客户端断开连接(Http协议要求)
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
